import React, {useEffect, useState} from 'react'
import {Badge, Breadcrumb, Button, Card, Drawer, Grid, Input, Layout, Spin, Tooltip, Typography} from 'antd'
import {Activity, Clock, Database, Menu as MenuIcon, RefreshCw, Search, Server, Table} from 'lucide-react'
import DataSourceTree from '@/components/business/DataSourceTree'
import {useDataSourceStore} from '@/stores/dataSourceStore'
import CatalogPanel from '@/components/business/CatalogPanel'
import DatabasePanel from '@/components/business/DatabasePanel'
import TablePanel from '@/components/business/TablePanel'
// 移除右侧详情面板，改为在中间展示目录详情

const { Sider, Content, Header } = Layout
const { useBreakpoint } = Grid

const App: React.FC = () => {
  const {
    treeData,
    loading,
    displayServer,
    displayTable,
    selectedNode,
    setSelectedNode,
    setDisplayOptions,
    loadTree,
  } = useDataSourceStore()

  const [drawerVisible, setDrawerVisible] = useState(false)
  const [lastUpdateTime, setLastUpdateTime] = useState<string>('')
  const [searchKeyword, setSearchKeyword] = useState<string>('')
  const screens = useBreakpoint()

  // 计算面包屑路径
  const getBreadcrumbItems = () => {
    const items = [{ title: '数据源中心', href: '#' }]

    if (selectedNode) {
      switch (selectedNode.nodeType) {
        case 'CATALOG':
          items.push({ title: selectedNode.title })
          break
        case 'DATABASE':
          items.push(
            { title: selectedNode.parentId || '目录', href: '#' },
            { title: selectedNode.title }
          )
          break
        case 'TABLE':
          items.push(
            { title: selectedNode.catalogName || '目录', href: '#' },
            { title: selectedNode.parentId || '数据库', href: '#' },
            { title: selectedNode.title }
          )
          break
      }
    }

    return items
  }

  // 过滤树数据的函数（支持模糊匹配）
  const filterTreeData = (data: any[], keyword: string): any[] => {
    if (!keyword.trim()) return data

    const normalizeString = (str: string) => {
      return str.toLowerCase().replace(/\s+/g, '')
    }

    const isMatch = (text: string, keyword: string) => {
      const normalizedText = normalizeString(text)
      const normalizedKeyword = normalizeString(keyword)

      // 支持模糊搜索：包含匹配、拼音首字母匹配等
      return normalizedText.includes(normalizedKeyword) ||
             text.toLowerCase().includes(keyword.toLowerCase())
    }

    const filterNode = (node: any): any | null => {
      const titleMatch = isMatch(node.title || '', keyword)
      const filteredChildren = node.children ? node.children.map(filterNode).filter(Boolean) : []

      // 如果当前节点匹配或有匹配的子节点，则保留
      if (titleMatch || filteredChildren.length > 0) {
        return {
          ...node,
          children: filteredChildren.length > 0 ? filteredChildren : node.children
        }
      }

      return null
    }

    return data.map(filterNode).filter(Boolean)
  }

  // 渲染侧边栏内容 - 整合设计
  const renderSiderContent = () => (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 整合的数据源管理面板 */}
      <Card
        style={{
          margin: '12px 8px',
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          borderRadius: 16,
          background: 'linear-gradient(145deg, #ffffff, #fafbfc)',
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.08)',
          border: '1px solid rgba(24, 144, 255, 0.08)'
        }}
        bodyStyle={{
          padding: 0,
          flex: 1,
          display: 'flex',
          flexDirection: 'column'
        }}
      >
        {/* 简洁的工具栏头部 */}
        <div
          className="sidebar-toolbar-compact"
          style={{
            padding: '14px 16px 10px',
            background: 'linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(248, 250, 252, 0.9))',
            borderRadius: '16px 16px 0 0',
            borderBottom: '1px solid rgba(240, 242, 245, 0.8)'
          }}
        >
          {/* 标题行 */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Database size={16} style={{ marginRight: 6, color: '#1890ff' }} />
              <Typography.Title level={5} style={{ margin: 0, color: '#1d2129', fontSize: 14, fontWeight: 600 }}>
                数据源
              </Typography.Title>
            </div>
          </div>

          {/* 紧凑的操作工具栏 */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              {/* 搜索输入框 */}
              <Input
                  size="small"
                  placeholder="搜索数据源..."
                  prefix={<Search size={10} style={{ color: '#bfbfbf' }} />}
                  value={searchKeyword}
                  onChange={(e) => setSearchKeyword(e.target.value)}
                  allowClear
                  className="sidebar-search-input"
                  style={{
                      width: 120,
                      height: 24,
                      borderRadius: 4,
                      fontSize: 11,
                      background: 'rgba(255, 255, 255, 0.8)',
                      border: '1px solid rgba(24, 144, 255, 0.15)'
                  }}
                  styles={{
                      input: {
                          fontSize: 11,
                          color: '#595959'
                      }
                  }}
              />
            {/* 显示选项按钮组 */}
            <div className="compact-button-group" style={{
              display: 'flex',
              alignItems: 'center',
              gap: 2,
              padding: '2px',
              background: 'rgba(24, 144, 255, 0.06)',
              borderRadius: 6,
              border: '1px solid rgba(24, 144, 255, 0.12)'
            }}>
                {/* 刷新按钮 */}
                <Tooltip title="服务器节点">
                    <Button
                        type={displayServer ? 'primary' : 'text'}
                        size="small"
                        icon={<Server size={11} />}
                        onClick={() => setDisplayOptions({ displayServer: !displayServer })}
                        className="compact-button"
                        style={{
                            minWidth: 24,
                            height: 24,
                            padding: 0,
                            borderRadius: 4,
                            background: displayServer ? '#52c41a' : 'transparent',
                            borderColor: 'transparent',
                            color: displayServer ? '#ffffff' : '#8c8c8c',
                            boxShadow: displayServer ? '0 1px 4px rgba(82, 196, 26, 0.4)' : 'none'
                        }}
                    />
                </Tooltip>
                <Tooltip title="表节点">
                    <Button
                        type={displayTable ? 'primary' : 'text'}
                        size="small"
                        icon={<Table size={11} />}
                        onClick={() => setDisplayOptions({ displayTable: !displayTable })}
                        className="compact-button"
                        style={{
                            minWidth: 24,
                            height: 24,
                            padding: 0,
                            borderRadius: 4,
                            background: displayTable ? '#52c41a' : 'transparent',
                            borderColor: 'transparent',
                            color: displayTable ? '#ffffff' : '#8c8c8c',
                            boxShadow: displayTable ? '0 1px 4px rgba(250, 173, 20, 0.4)' : 'none'
                        }}
                    />
                </Tooltip>
                <Tooltip title="刷新数据源">
                    <Button
                        type="primary"
                        size="small"
                        icon={<RefreshCw size={11} />}
                        loading={loading}
                        onClick={() => {
                            loadTree().then(() => {
                                setLastUpdateTime(new Date().toLocaleTimeString())
                            })
                        }}
                        style={{
                            minWidth: 28,
                            height: 24,
                            borderRadius: 4,
                            background: loading ? '#d9d9d9' : 'linear-gradient(135deg, #1890ff, #40a9ff)',
                            border: 'none',
                            boxShadow: loading ? 'none' : '0 1px 4px rgba(24, 144, 255, 0.4)',
                            transition: 'all 0.2s ease'
                        }}
                    />
                </Tooltip>
            </div>
          </div>
        </div>
          {/* 优化的树形组件区域 */}
          <div style={{
              flex: 1,
              padding: '8px 12px 12px',
              overflow: 'auto',
              background: 'linear-gradient(135deg, rgba(255, 255, 255, 0.7), rgba(250, 251, 252, 0.7))'
          }}>
              {loading ? (
                  <div className="loading-state-container" style={{
                      textAlign: 'center',
                      padding: '40px 16px',
                      background: 'rgba(255, 255, 255, 0.5)',
                      borderRadius: 12,
                      border: '1px dashed rgba(24, 144, 255, 0.2)'
                  }}>
                      <div className="empty-state-icon" style={{
                          width: 48,
                          height: 48,
                          borderRadius: 24,
                          background: 'linear-gradient(135deg, rgba(24, 144, 255, 0.1), rgba(24, 144, 255, 0.2))',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          margin: '0 auto 12px'
                      }}>
                          <Spin size="default" />
                      </div>
                      <Typography.Text style={{ display: 'block', fontSize: 12, color: '#8c8c8c' }}>
                          正在加载数据源...
                      </Typography.Text>
                  </div>
              ) : treeData.length === 0 ? (
                  <div className="empty-state-container" style={{
                      textAlign: 'center',
                      padding: '40px 16px',
                      background: 'rgba(255, 255, 255, 0.5)',
                      borderRadius: 12,
                      border: '1px dashed rgba(217, 217, 217, 0.5)'
                  }}>
                      <div
                          className="empty-state-icon"
                          style={{
                              width: 48,
                              height: 48,
                              borderRadius: 24,
                              background: 'linear-gradient(135deg, rgba(217, 217, 217, 0.1), rgba(217, 217, 217, 0.2))',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              margin: '0 auto 12px'
                          }}
                      >
                          <Database size={20} style={{ color: '#d9d9d9' }} />
                      </div>
                      <Typography.Text strong style={{ display: 'block', fontSize: 13, color: '#8c8c8c', marginBottom: 6 }}>
                          暂无数据源
                      </Typography.Text>
                      <Typography.Text style={{ fontSize: 11, color: '#bfbfbf', lineHeight: 1.4, marginBottom: 12 }}>
                          请检查后端服务状态或点击刷新重试
                      </Typography.Text>
                      <Button
                          type="link"
                          size="small"
                          icon={<RefreshCw size={10} />}
                          onClick={() => {
                              loadTree().then(() => {
                                  setLastUpdateTime(new Date().toLocaleTimeString())
                              })
                          }}
                          style={{
                              padding: '2px 8px',
                              height: 20,
                              fontSize: 11,
                              color: '#1890ff'
                          }}
                      >
                          立即刷新
                      </Button>
                  </div>
              ) : (
                  <div className="tree-container" style={{
                      background: 'rgba(255, 255, 255, 0.8)',
                      borderRadius: 8,
                      padding: '8px 4px',
                      border: '1px solid rgba(240, 242, 245, 0.8)',
                      minHeight: 200
                  }}>
                      {(() => {
                          const filteredData = filterTreeData(treeData, searchKeyword)
                          return filteredData.length === 0 && searchKeyword.trim() ? (
                              <div className="search-empty-result" style={{
                                  textAlign: 'center',
                                  padding: '40px 16px',
                                  color: '#8c8c8c',
                                  borderRadius: 8,
                                  background: 'rgba(255, 255, 255, 0.2)',
                                  border: '1px dashed rgba(217, 217, 217, 0.5)'
                              }}>
                                  <div style={{
                                      width: 40,
                                      height: 40,
                                      borderRadius: 20,
                                      background: 'linear-gradient(135deg, rgba(217, 217, 217, 0.1), rgba(217, 217, 217, 0.2))',
                                      display: 'flex',
                                      alignItems: 'center',
                                      justifyContent: 'center',
                                      margin: '0 auto 12px'
                                  }}>
                                      <Search size={18} style={{ color: '#d9d9d9' }} />
                                  </div>
                                  <Typography.Text strong style={{ display: 'block', fontSize: 12, color: '#8c8c8c', marginBottom: 4 }}>
                                      未找到匹配的数据源
                                  </Typography.Text>
                                  <Typography.Text style={{ fontSize: 11, color: '#bfbfbf', lineHeight: 1.4 }}>
                                      请尝试其他关键词搜索
                                  </Typography.Text>
                              </div>
                          ) : (
                              <DataSourceTree
                                  data={filteredData}
                                  loading={loading}
                                  displayServer={displayServer}
                                  displayTable={displayTable}
                                  selectedKeys={selectedNode ? [selectedNode.id] : []}
                                  onSelect={(node) => {
                                      setSelectedNode(node)
                                      // 移动端选择后自动关闭抽屉
                                      if (!screens.lg) {
                                          setDrawerVisible(false)
                                      }
                                  }}
                              />
                          )
                      })()}
                  </div>
              )}
          </div>
      </Card>
    </div>
  )

  useEffect(() => {
    loadTree().then(() => {
      setLastUpdateTime(new Date().toLocaleTimeString())
    })
  }, [displayServer, displayTable])

  // @ts-ignore
    return (
    <Layout style={{ height: '100vh' }}>
      <Header className="app-header">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: '100%' }}>
          <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
            {/* 移动端菜单按钮 */}
            {!screens.lg && (
              <Button
                type="text"
                icon={<MenuIcon size={20} style={{ color: '#ffffff' }} />}
                onClick={() => setDrawerVisible(true)}
                style={{ marginRight: 12, border: 'none', background: 'transparent' }}
              />
            )}

            <div className="app-header-title">
              <Database size={24} style={{ marginRight: 8, verticalAlign: 'middle' }} />
              数据源中心
            </div>

            {/* 面包屑导航 */}
            {selectedNode && screens.md && (
              <div style={{ marginLeft: 24, flex: 1 }}>
                <Breadcrumb
                  items={getBreadcrumbItems()}
                  style={{
                    color: 'rgba(255, 255, 255, 0.85)',
                  }}
                />
              </div>
            )}
          </div>

          {/* 右侧状态信息 */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            {/* 活动状态 */}
            <Tooltip title="数据源连接状态">
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <Activity size={16} style={{ color: '#52c41a' }} />
                <Typography.Text style={{ color: 'rgba(255, 255, 255, 0.85)', fontSize: 12 }}>
                  在线
                </Typography.Text>
              </div>
            </Tooltip>

            {/* 数据源计数 */}
            <Tooltip title="数据源总数">
              <Badge
                count={treeData.length}
                style={{ backgroundColor: 'rgba(255, 255, 255, 0.2)' }}
                showZero
              />
            </Tooltip>

            {/* 最后更新时间 */}
            {lastUpdateTime && screens.sm && (
              <Tooltip title={`最后更新时间: ${lastUpdateTime}`}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <Clock size={14} style={{ color: 'rgba(255, 255, 255, 0.65)' }} />
                  <Typography.Text style={{ color: 'rgba(255, 255, 255, 0.65)', fontSize: 11 }}>
                    {lastUpdateTime}
                  </Typography.Text>
                </div>
              </Tooltip>
            )}

            {/* 版本信息 */}
            <Typography.Text style={{ color: 'rgba(255, 255, 255, 0.65)', fontSize: 11 }}>
              v1.0.0
            </Typography.Text>
          </div>
        </div>
      </Header>
      <Layout>
        {/* 桌面端侧边栏 */}
        {screens.lg && (
          <Sider
            width={screens.xl ? 320 : 280}
            theme="light"
            style={{
              borderRight: '1px solid #f0f2f5',
              overflow: 'auto',
              background: 'linear-gradient(180deg, #ffffff 0%, #fafbfc 100%)',
              boxShadow: '2px 0 8px rgba(0, 0, 0, 0.06)'
            }}
          >
            {renderSiderContent()}
          </Sider>
        )}

        {/* 移动端抽屉 */}
        <Drawer
          title={
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Database size={18} style={{ marginRight: 8, color: '#1890ff' }} />
              数据源管理
            </div>
          }
          placement="left"
          onClose={() => setDrawerVisible(false)}
          open={drawerVisible}
          width={screens.sm ? 360 : '85%'}
          styles={{
            body: { padding: 0 },
            header: { background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', color: '#ffffff' }
          }}
        >
          <div style={{ background: 'linear-gradient(180deg, #ffffff 0%, #fafbfc 100%)', height: '100%' }}>
            {renderSiderContent()}
          </div>
        </Drawer>
        <Content
          style={{
            padding: screens.xs ? '12px' : screens.sm ? '16px' : '24px',
            overflow: 'auto',
            background: 'linear-gradient(135deg, #f5f7fa 0%, #f8fafc 100%)',
            minHeight: 'calc(100vh - 64px)'
          }}
        >
          <div className="page-container" style={{ maxWidth: screens.xl ? '1400px' : '1200px' }}>
            {/* 移动端面包屑 */}
            {selectedNode && !screens.md && (
              <Card
                size="small"
                style={{
                  marginBottom: 16,
                  background: 'rgba(255, 255, 255, 0.9)',
                  backdropFilter: 'blur(8px)',
                  border: '1px solid rgba(255, 255, 255, 0.2)'
                }}
              >
                <Breadcrumb items={getBreadcrumbItems()} />
              </Card>
            )}

            {/* 欢迎页面 - 优化版 */}
            {!selectedNode && (
              <Card
                style={{
                  textAlign: 'center',
                  padding: screens.xs ? '20px 16px' : '60px 40px',
                  border: 'none',
                  background: 'linear-gradient(145deg, #ffffff, #fafbfc)',
                  borderRadius: 24,
                  boxShadow: '0 8px 32px rgba(0, 0, 0, 0.08)',
                  position: 'relative',
                  overflow: 'hidden'
                }}
              >
                {/* 背景装饰 */}
                <div
                  style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'radial-gradient(circle at 30% 20%, rgba(24, 144, 255, 0.05), transparent 50%)',
                    zIndex: 0
                  }}
                />

                <div style={{ position: 'relative', zIndex: 1 }}>
                  <div style={{ marginBottom: screens.xs ? 16 : 32 }}>
                    <Database
                      size={screens.xs ? 36 : 64}
                      style={{
                        color: '#1890ff',
                        marginBottom: screens.xs ? 12 : 24,
                        filter: 'drop-shadow(0 4px 12px rgba(24, 144, 255, 0.3))'
                      }}
                    />
                  </div>

                  <Typography.Title
                    level={screens.xs ? 3 : 1}
                    style={{
                      marginTop: 0,
                      marginBottom: screens.xs ? 12 : 24,
                      color: '#1d2129',
                      background: 'linear-gradient(135deg, #1890ff, #52c41a)',
                      WebkitBackgroundClip: 'text',
                      WebkitTextFillColor: 'transparent',
                      backgroundClip: 'text'
                    }}
                  >
                    🚀 数据源中心
                  </Typography.Title>

                  <Typography.Paragraph
                    style={{
                      fontSize: screens.xs ? 14 : 18,
                      color: '#4e5969',
                      marginBottom: screens.xs ? 24 : 40,
                      maxWidth: 600,
                      margin: '0 auto',
                      lineHeight: 1.6
                    }}
                  >
                    统一管理数据源、数据库和表结构
                    <br />
                    {!screens.lg && '点击左上角菜单开始使用'}
                    {screens.lg && '从左侧面板选择数据源开始管理'}
                  </Typography.Paragraph>

                  {/* 功能卡片 */}
                  <div
                    style={{
                      display: 'grid',
                      gridTemplateColumns: screens.xs ? '1fr' : screens.sm ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)',
                      gap: screens.xs ? 16 : 24,
                      maxWidth: 800,
                      margin: '0 auto'
                    }}
                  >
                    <Card
                      hoverable
                      size="small"
                      style={{
                        background: 'linear-gradient(135deg, rgba(82, 196, 26, 0.05), rgba(82, 196, 26, 0.1))',
                        border: '1px solid rgba(82, 196, 26, 0.2)',
                        borderRadius: 16
                      }}
                    >
                      <div style={{ textAlign: 'center', padding: 16 }}>
                        <Server size={32} style={{ color: '#52c41a', marginBottom: 12 }} />
                        <Typography.Text strong style={{ display: 'block', fontSize: 14, marginBottom: 4 }}>
                          服务器管理
                        </Typography.Text>
                        <Typography.Text style={{ fontSize: 12, color: '#86909c' }}>
                          连接测试与状态监控
                        </Typography.Text>
                      </div>
                    </Card>

                    <Card
                      hoverable
                      size="small"
                      style={{
                        background: 'linear-gradient(135deg, rgba(250, 173, 20, 0.05), rgba(250, 173, 20, 0.1))',
                        border: '1px solid rgba(250, 173, 20, 0.2)',
                        borderRadius: 16
                      }}
                    >
                      <div style={{ textAlign: 'center', padding: 16 }}>
                        <Database size={32} style={{ color: '#faad14', marginBottom: 12 }} />
                        <Typography.Text strong style={{ display: 'block', fontSize: 14, marginBottom: 4 }}>
                          数据库管理
                        </Typography.Text>
                        <Typography.Text style={{ fontSize: 12, color: '#86909c' }}>
                          同步与配置管理
                        </Typography.Text>
                      </div>
                    </Card>

                    <Card
                      hoverable
                      size="small"
                      style={{
                        background: 'linear-gradient(135deg, rgba(255, 77, 79, 0.05), rgba(255, 77, 79, 0.1))',
                        border: '1px solid rgba(255, 77, 79, 0.2)',
                        borderRadius: 16,
                        gridColumn: screens.sm && !screens.lg ? 'span 2' : 'auto'
                      }}
                    >
                      <div style={{ textAlign: 'center', padding: 16 }}>
                        <Table size={32} style={{ color: '#ff4d4f', marginBottom: 12 }} />
                        <Typography.Text strong style={{ display: 'block', fontSize: 14, marginBottom: 4 }}>
                          表结构管理
                        </Typography.Text>
                        <Typography.Text style={{ fontSize: 12, color: '#86909c' }}>
                          字段与维度配置
                        </Typography.Text>
                      </div>
                    </Card>
                  </div>

                  {/* 快捷操作 */}
                  {!screens.lg && (
                    <div style={{ marginTop: 32 }}>
                      <Button
                        type="primary"
                        size="large"
                        icon={<MenuIcon size={18} />}
                        onClick={() => setDrawerVisible(true)}
                        style={{
                          background: 'linear-gradient(135deg, #1890ff, #40a9ff)',
                          border: 'none',
                          borderRadius: 12,
                          padding: '0 32px',
                          height: 48
                        }}
                      >
                        打开数据源面板
                      </Button>
                    </div>
                  )}
                </div>
              </Card>
            )}

            {/* 内容面板 */}
            {selectedNode?.nodeType === 'CATALOG' && (
              <div style={{ animation: 'fadeInUp 0.3s ease-out' }}>
                <CatalogPanel node={selectedNode} />
              </div>
            )}
            {selectedNode?.nodeType === 'DATABASE' && (
              <div style={{ animation: 'fadeInUp 0.3s ease-out' }}>
                <DatabasePanel node={selectedNode} />
              </div>
            )}
            {selectedNode?.nodeType === 'TABLE' && (
              <div style={{ animation: 'fadeInUp 0.3s ease-out' }}>
                <TablePanel node={selectedNode} />
              </div>
            )}
          </div>
        </Content>
      </Layout>
    </Layout>
  )
}

export default App